package com.byedu.course.controller;

import com.alibaba.fastjson.JSON;
import com.byedu.course.*;
import com.byedu.domain.course.vo.enumvos.*;
import com.byedu.domain.course.vo.*;
import com.byedu.domain.course.CourseDO;
import com.byedu.domain.course.LibraryDO;
import com.byedu.model.constants.CharsetType;
import com.byedu.model.constants.FileType;
import com.byedu.util.CommonUtil;
import com.byedu.util.FileUploadUtil;
import com.byedu.util.FileUtil;
import com.byedu.util.ZipUtil;
import com.byedu.util.page.PageUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by Luo on 2017-06-28.
 */
@Controller
@RequestMapping("/clazz")
public class AdminClazzController {

    private static final Logger logger = LoggerFactory.getLogger(AdminClazzController.class);


    @Value("${admin.library.upload.filepath}")
    private String baseDir;

    @Value("${admin.library.upload.copyfilepath}")
    private String copyDir;
    @Autowired
    private UserCourseService userCourseService;
    @Autowired
    private LibraryService libraryService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private AnswerService answerService;
    @Autowired
    private QuestionService questionService;

    @Autowired
    private LibQuestionTempService libQuestionTempService;


    @RequestMapping("index")
    public String defaultr(HttpServletRequest request){
        String m = request.getParameter("m");
        if(StringUtils.isEmpty(m)){
            m = "clazz";
        }
        request.setAttribute("m", m);
        request.setAttribute("newsnum", 100);
        request.setAttribute("clazznum", 20);
        request.setAttribute("sourcenum", 30);
        request.setAttribute("topicnum", 50);
        return "index";
    }

    @RequestMapping("/industryList")
    public String  industryList(HttpServletRequest request){
        String m = request.getParameter("m");

        List<IndustryEnumVO> allIndustryEnums = libraryService.listIndustryEnum();
//        PageUtil.save(request);
        request.setAttribute("allIndustryList", allIndustryEnums);

        return "clazz/clazzInslist";
    }

    @RequestMapping("changeLib")
    public String  changeLib(HttpServletRequest request,HttpServletResponse response){
        String m = request.getParameter("m");

        List<IndustryEnumVO> allIndustryEnums = libraryService.listIndustryEnum();
       CommonUtil.outpostprint(response, JSON.toJSONString(allIndustryEnums));

        return null;
    }
    @RequestMapping("clazzdel")
    public String  clazzdel(@RequestParam(value = "id", required = false) Integer id ,HttpServletRequest request,HttpServletResponse response){
        try {

            courseService.delCourse(id);

            response.sendRedirect(request.getContextPath() + "/clazz/clazzList?m=list");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @RequestMapping("/clazzList")
    public String clazzList(HttpServletRequest request) {
        String m = request.getParameter("m");
        if("edit".equals(m)){
            List<IndustryEnumVO> allIndustryEnums = libraryService.listIndustryEnum();
            request.setAttribute("industryList", allIndustryEnums);
            return "clazz/addclazz";
        }
        if("add".equals(m)){
            List<IndustryEnumVO> allIndustryEnums = libraryService.listIndustryEnum();
            request.setAttribute("industryList", allIndustryEnums);
            return "clazz/addclazz";
        }
        if("list".equals(m)){
            String industry = request.getParameter("industryId");
            List<CourseBuyVO> allcourses = null;
            if (StringUtils.isEmpty(industry) || "0".equals(industry)) {
                allcourses = courseService.listallBuyCourses();

            } else {
                allcourses = courseService.listCourseBuysbyIndustry(industry);
            }
            PageUtil.save(request);
            List<IndustryEnumVO> allIndustryEnums = libraryService.listIndustryEnum();
//        PageUtil.save(request);
            request.setAttribute("industryList", allIndustryEnums);
            request.setAttribute("clazzList", allcourses);

            return "clazz/clazzList";
        }

        return "clazz/clazzList";
    }

    @RequestMapping("/clazzlabadd")
    public String clazzedit(HttpServletRequest request,HttpServletResponse response){
        String m = request.getParameter("m");

        if("add".equals(m)){
            return "clazz/addclalab";
        }
        if("dopub".equals(m)) {
            CommonUtil.outpostprint(response,"1");
        }
        return null;
    }

    @RequestMapping("/clazzuserList")
    public String clazzuserList(HttpServletRequest request){

        List<UserCourseVO> userCourseVOList =userCourseService.getAllUserCourse();
        request.setAttribute("clazzList", userCourseVOList);
        PageUtil.save(request);
        return "clazz/clazzuserList";
    }

    @RequestMapping("/clazzLibraryList")
    public String clazzLibraryList(HttpServletRequest request,HttpServletResponse response){
        String m = request.getParameter("m");

        if("del".equals(m)) {
            int pid = CommonUtil.StringToInt(request.getParameter("id"));
            libraryService.del(pid);
            try {
                response.sendRedirect(request.getContextPath() + "/clazz/clazzLibraryList?m=list");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }else{

            List<LibraryVO> libraryVOList;
            int pid = CommonUtil.StringToInt(request.getParameter("clazzId"));
            if (pid==0) {

                libraryVOList = libraryService.listAllLibraries();
            }else{

                libraryVOList =  libraryService.listLibrariesByCourseId(pid);;
            }

            List<CourseVO> courseVOList = courseService.listallCourses();
//        List<LibraryTypeEnumVO> libraryTypeEnumList = libraryService.listLibraryEnum();

            request.setAttribute("courseList", courseVOList);
            request.setAttribute("libraryList", libraryVOList);
//        request.setAttribute("libraryTypeList", libraryTypeEnumList);

            PageUtil.save(request);


        }
        return "clazz/clazzLibraryList";
    }

    @RequestMapping("/clazzLibraryadd")
    public String clazzLibraryadd(HttpServletRequest request,HttpServletResponse response,
                                  @RequestParam(value = "name", required = false) String name ,
                                  @RequestParam(value = "courseId", required = false) String courseId,
                                  @RequestParam(value = "trialNum", required = false) String trialNum,
                                  @RequestParam(value = "libraryType", required = false) String libraryType){


        String m = request.getParameter("m");

        if("to".equals(m)) {


            List<CourseVO> courseVOList = courseService.listallCourses();
            List<LibraryTypeEnumVO> libraryTypeEnumList = libraryService.listLibraryEnum();

            request.setAttribute("courseList", courseVOList);
            request.setAttribute("libraryTypeList", libraryTypeEnumList);

            return "clazz/updatequestion";
        }else{
            try {
                LibraryDO libraryDO = new LibraryDO();
                libraryDO.setName(name);
                libraryDO.setCourseId(Integer.parseInt(courseId));
                libraryDO.setLibraryType(libraryType);
                libraryDO.setTrialNum(Integer.parseInt(trialNum));

//                    libraryService.saveLibrary(libraryVO);

                response.sendRedirect(request.getContextPath() + "/clazz/clazzLibraryList?m=list");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }




    @RequestMapping("/clazzquestionList")
    public String clazzquestionList(HttpServletRequest request){

        String m = request.getParameter("m");

        if("list".equals(m)) {
            int pid = CommonUtil.StringToInt(request.getParameter("pid"));
            int courseId = CommonUtil.StringToInt(request.getParameter("courseId"));
            List<QuestionVO> listQuestions;
            List<LibraryVO> listLibrarys;
            List<CourseVO> courseVOList = courseService.listallCourses();
//        List<LibraryTypeEnumVO> libraryTypeEnumList = libraryService.listLibraryEnum();

            if (0 != pid) {

                listQuestions = questionService.listQuestionsByLibraryId(pid);
                if (CollectionUtils.isNotEmpty(listQuestions)) {
                    courseId = libraryService.getLibraryDOById(pid).getCourseId();
                }
                request.setAttribute("menuList", listQuestions);
            }
            if (0 != courseId) {

                listLibrarys = libraryService.listLibrariesByCourseId(courseId);
                request.setAttribute("topLibList", listLibrarys);
                System.out.print("listLibrarys---" + listLibrarys);
            }


            request.setAttribute("courseList", courseVOList);


            PageUtil.save(request);

            return "clazz/clazzquestionList";
        }
        if("add".equals(m)){
            List<CourseVO> courseList = courseService.listallCourses();
            List<LibraryTypeEnumVO> libraryTypeEnumList = libraryService.listLibraryEnum();

            request.setAttribute("courseList", courseList);
            request.setAttribute("libraryTypeList", libraryTypeEnumList);
            return "clazz/uploadquestions";
        }

        return "clazz/clazzquestionList";
    }

    @RequestMapping("/clazzadd")
    public String clazzadd(
            @RequestParam(value = "name", required = false) String name ,
            @RequestParam(value = "intro", required = false) String intro,
            @RequestParam(value = "price", required = false) String price,
            @RequestParam(value = "openTime", required = false) String openTime,
            @RequestParam(value = "industryId", required = false) String industryId,
            HttpServletRequest request,HttpServletResponse response){
        String m = request.getParameter("m");

        if("to".equals(m)){
            List<IndustryEnumVO> allIndustryEnums = libraryService.listIndustryEnum();
            request.setAttribute("industryList", allIndustryEnums);
            return "clazz/addclazz";
        }else {
            String  img = new FileUploadUtil().saveOneFile(request,"clazz");
            if(img==null){
                CommonUtil.outpostprint(response,"上传文件出错");
                return null;
            }
            try {
                CourseDO courseDO = new CourseDO();
                courseDO.setName(name);
                courseDO.setPrice(Integer.parseInt(price));
                courseDO.setIndustry(industryId);
                courseDO.setIntro(intro);
                courseDO.setImg(img);
                courseDO.setOpenTime(openTime);
                int num=courseService.saveCourses(courseDO);
                if(num>0) {
                    response.sendRedirect(request.getContextPath() + "/clazz/clazzList?m=list");
                }else{
                    CommonUtil.outpostprint(response,"数据存储错误");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

    }

    @RequestMapping("/clazzuploadquestions")
    public String uploadquestions(HttpServletRequest request){
        String m = request.getParameter("m");

        List<CourseVO> courseList = courseService.listallCourses();
        List<LibraryTypeEnumVO> libraryTypeEnumList = libraryService.listLibraryEnum();

            request.setAttribute("courseList", courseList);
            request.setAttribute("libraryTypeList", libraryTypeEnumList);
        return "clazz/uploadquestions";
    }

    @RequestMapping(value = "uploadFile", method = RequestMethod.POST)
    public String uploadFile(
            @RequestParam(value = "courseId") Integer courseId,
            @RequestParam(value = "libraryType") String libraryType,
            @RequestParam(value = "trial_num") Integer trial_num,
            @RequestParam("multipartFile") CommonsMultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response){
        try {

    //要先删除所有文件 错题干扰重复上传
        File ulfile=  new File(baseDir);
        FileUtil.deleteFile(ulfile);

        //获取题库名称
        String fileName = multipartFile.getOriginalFilename().replace("/","").replace("\\","");
        String[] tmpStrAry = fileName.split("[.]");
        String fileType = tmpStrAry[1];
            LibraryDO libraryDO = new LibraryDO();
            libraryDO.setCourseId(courseId);
            libraryDO.setLibType(libraryType);
            libraryDO.setLibraryType(libraryType);

            libraryDO.setTrialNum(trial_num);
            int filesize =  (int)multipartFile.getSize();
            DiskFileItem diskFileItem = (DiskFileItem) multipartFile.getFileItem();
            File file = diskFileItem.getStoreLocation();
            String dirPath = baseDir + File.separator +courseId + File.separator;
            String copyDirdirPath = copyDir + File.separator +courseId + File.separator;

            //zip类型，解压然后再解析。
         if(FileType.ZIP.getValue().equals(fileType)){
             List<String> listStr = ZipUtil.unzip(file, dirPath, copyDirdirPath, CharsetType.GBK.getValue());
             questionService.analyzeFlieQuestions(listStr, libraryDO);
         }
         //将excel进行保存
         else if(FileType.XLSX.getValue().equals(fileType)){
             String myfileName =ZipUtil.saveExcel(filesize,file,fileName,dirPath,copyDirdirPath);
             questionService.analyzeQuestion(new File(myfileName), libraryDO);

         }else {
             CommonUtil.outpostprint(response,"文件不是zip，或者excel!!!<br/>");
             return null;
         }
            //进入统一解析



            response.sendRedirect(request.getContextPath() + "/clazz/clazzquestionList?m=list");
        return null;
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            CommonUtil.outpostprint(response,"请修复!!!<br/>"+e.getMessage());
        }
        return null;
    }


}
